package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/6
 */
@Slf4j
public class Thread_6_保护性暂停模式 {
    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(() -> {
            log.info("等待结果");
            try {
                List<String> list = (List<String>) guardedObject.get(10000);
                log.info("结果大小：" + list.size());
            } catch (NullPointerException e) {
                log.info("超时等待");
            }

        }, "t1").start();
        new Thread(() -> {
            log.info("等待结果");
            try {
                List<String> list = Downloader.download();
                guardedObject.complete(list);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }
}

class Downloader {
    public static List<String> download() throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL("https://www.baidu.com").openConnection();
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }
}

class GuardedObject {
    //    结果
    private Object response;

    //    获取结果
    public Object get(long timeout) {
        synchronized (this) {
            long begin = System.currentTimeMillis();
//            没有结果
            long passedTime = 0;
            while (response == null) {
//                这一轮循环应该等待的时间
                long waitTime = timeout - passedTime;
                if (waitTime <= 0) {
                    break;
                }
                try {
                    this.wait(waitTime);
                    passedTime = System.currentTimeMillis();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
    }

    //    产生结果
    public void complete(Object response) {
        synchronized (this) {
//            给姐u共成员变量赋值
            this.response = response;
            this.notifyAll();
        }
    }
}
